package com.scenic.adminservice.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageInfo;
import com.scenic.common.bean.Admin;
import com.scenic.common.bean.RespBean;
import com.scenic.common.exception.ScenicSpotException;
import com.scenic.common.service.AdminService;
import com.scenic.common.utils.JwtUtils;
import com.scenic.common.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AdminService adminService;
    @GetMapping("/captcha")
    public RespBean captcha(){
        //创建验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 38, 4, 10);
        //生成唯一的key - 雪花算法
        String key = IdUtil.getSnowflakeNextIdStr();
        redisUtil.set(key, captcha.getCode(),60);
        //将验证码图片转换成Base64编码形式
        String imageBase64Data = captcha.getImageBase64Data();
        //将key和Base64保存在map中
        HashMap<String, Object> map = new HashMap<>();
        map.put("key", key);
        map.put("imageBase64Data",imageBase64Data);
        //将key和Base图片返回
        return RespBean.ok("生成验证码成功",map);
    }

    @PostMapping("/login")
    public RespBean login(String username,
                          String password,
                          String key,
                          String captchaInput) throws ScenicSpotException {
        //判断验证码是否正确 - 从redis中查询验证码是否存在
        String captcha = (String)redisUtil.get(key);
        if (captcha == null || !captcha.equalsIgnoreCase(captchaInput)) {
            throw new ScenicSpotException("验证码错误，请重新生成验证码");
        }
        //登录
        Admin admin = adminService.login(username, password);
        //生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        map.put("role", "admin");
        //将token返回给用户
        String jwt = JwtUtils.generateJwt(map);
        return RespBean.ok("登录成功",jwt);
    }
    //获取已登录的信息
    @GetMapping("/info")
    public RespBean getLogin(@RequestHeader("token") String token){
        //解析token
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer id = (Integer)map.get("id");
        Admin admin = adminService.selectById(id);
        //返回
        return RespBean.ok("",admin);
    }
    @PutMapping("/chgPwd")
    //修改密码
    public RespBean chgPwd(@RequestHeader("token") String token,
                           String oldPwd,
                           String newPwd,
                           String newPwd1) throws ScenicSpotException {
        if (!newPwd.equals(newPwd1)) {
            throw new ScenicSpotException("两次输入的新密码不一致，无法修改");
        }
        //解析token
        Map<String, Object> map = JwtUtils.parseJwtToMap(token);
        //获取用户id - 根据id查询用户信息
        Integer id = (Integer)map.get("id");
        adminService.chgPwd(oldPwd, newPwd,id);

        return RespBean.ok("修改成功");
    }
    //添加
    @PostMapping
    public RespBean insert(@RequestBody Admin admin) throws ScenicSpotException {
        admin.setSalt("12345678");
        admin.setCreateTime(new Date());
        if (!adminService.insert(admin)) {
            return RespBean.ok("添加失败");
        }
        return RespBean.ok("添加成功");
    }
    //根据id删除
    @DeleteMapping(("/{id}"))
    public RespBean delete(@PathVariable("id") Integer id) throws ScenicSpotException {
        if (!adminService.delete(id)) {
            return RespBean.ok("禁用失败");
        }

        return RespBean.ok("禁用成功");
    }
    //根据id修改
    @PutMapping
    public RespBean update(@RequestBody Admin admin) throws ScenicSpotException {
        if (!adminService.update(admin)) {
            return RespBean.ok("修改失败");
        }
        return RespBean.ok("修改成功");
    }
    //条件分页搜索
    @GetMapping
    public RespBean selectByPage (Admin condition, Integer pageNum, Integer pageSize){
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        PageInfo<Admin> pageInfo = adminService.selectByCondition(condition, pageNum, pageSize);

        return RespBean.ok("",pageInfo);
    }
    //根据id查询
    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id){
        return RespBean.ok("",adminService.selectById(id));
    }
}
